//index.js
const utils = require("../../utils/util.js");
//获取应用实例
const myCards = require("../../mock/data/my").splice(0, 1);
const recivedCards = require("../../mock/data/recived");
const unrecivedCards = require("../../mock/data/unrecived");
const app = getApp();

Page({
  data: {
    orderType: "0",
    userId: "", // 用来区分已接收名片家中自己添加的名片还是别人的名片
    motto: "Hello World",
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse("button.open-type.getUserInfo"),
    myCards: [],
    showResult: false,
    unrecivedCards: [],
    unrecivedCardsTotal: 0,
    recivedCards: [],
    shareCardId: "", // 用于保存打开被人分享出来的名片的cardId
    pageNo: 1,
    total: 0,
    controlShow: false,
  },

  detectCard(path) {
    // 先查看用户有几张名片
    const myCardsLen = this.data.myCards.length;
    // 识别名片信息
    utils
      .ajax(
        // "/v1/bcs/uploadCustBusinessCard.do",
        "/v1/bcs/detectBusinessCard.do",
        {},
        {
          name: "businessCardFile",
          path: path,
        },
      )
      .then(res => {
        wx.hideLoading();
        if (res.code === "000000") {
          wx.navigateTo({
            url:
              "/pages/edit-card/edit-card?" +
              utils.serializeUrl(
                Object.assign({}, res.data.businessCardInfo, {
                  customerPicturePosition: "custom",
                  cardId: myCardsLen == 0 ? "" : "other",
                }),
              ),
          });
        } else {
          utils.message(res.message);
        }
      })
      .catch(res => {
        wx.hideLoading();
      });
  },
  takePhoto(event) {
    const _this = this;
    if (event.currentTarget.dataset.type == "camera") {
      wx.chooseImage({
        count: 1,
        sourceType: ["camera"],
        success: function(res) {
          _this.detectCard(res.tempFiles[0].path);
          wx.showLoading({
            mask: true,
            title: "正在识别中...",
          });
        },
        fail(res) {
          utils.message("图片选择失败");
        },
      });
    }
    if (event.currentTarget.dataset.type == "photo") {
      wx.chooseImage({
        count: 1,
        sourceType: ["album"],
        success: function(res) {
          _this.detectCard(res.tempFiles[0].path);
          wx.showLoading({
            mask: true,
            title: "正在识别中...",
          });
        },
        fail(res) {
          utils.message("图片选择失败");
        },
      });
    }
  },
  getUnreciveList() {
    // 获取待接收名片
    utils
      .ajax("/v1/bcs/queryWait4ConfirmUserCardHolders.do", {
        pageNo: 1,
        pageSize: 10,
      })
      .then(res => {
        if (res.code === "000000") {
          this.setData({
            unrecivedCards: res.data.datas,
            unrecivedCardsTotal: res.data.total,
          });
          this.getReciveList();
        } else {
          utils.logger(res.message || "获取待接收名片失败");
        }
      })
      .catch(res => {
        utils.message(res.message || "网络错误");
      });
  },
  getReciveList() {
    // 获取已接收名片
    utils
      .ajax("/v1/bcs/queryUserCardHolders.do", {
        pageNo: this.data.pageNo,
        pageSize: 10,
        orderType: this.data.orderType,
      })
      .then(res => {
        if (res.code === "000000") {
          this.setData({
            recivedCards: res.data.datas,
            total: res.data.total,
          });
        } else {
          utils.logger(res.message || "获取已接收名片失败");
        }
      })
      .catch(res => {
        utils.message(res.message || "网络错误");
      });
  },
  getMyCards() {
    utils
      .ajax("/v1/bcs/queryUserCards.do")
      .then(res => {
        if (res.code === "000000") {
          let _res = res;
          this.setData({
            myCards: res.data.userCards,
          });
          getApp().globalData["myCards"] = res.data.userCards;
          this.getUnreciveList();
        } else {
          utils.logger(res.message || "获取用户名片列表失败");
        }
      })
      .catch(res => {
        utils.logger(res, "获取用户名片列表失败： 网络错误");
      });
  },
  onLoad(options) {
    utils.logger("options", options);
    if (options.shareCardId) {
      this.setData({
        shareCardId: options.shareCardId,
      });
    }
  },
  onShow() {
    utils.logger("getApp().globalData", getApp().globalData);

    // 处理其他启动状态
    let scene = getApp().globalData["scene"];
    utils.logger(
      `this.data.shareCardId !== "",
      ["1007", "1008"].indexOf(String(scene)) >= 0,`,
    );
    utils.logger(
      this.data.shareCardId !== "",
      ["1007", "1008"].indexOf(String(scene)) >= 0,
    );
    if (
      this.data.shareCardId !== "" &&
      ["1007", "1008"].indexOf(String(scene)) >= 0
    ) {
      utils.logger("通过单聊或者群聊分享名片模式进入首页");
    }

    utils.logger(`[
      getApp().globalData["shareCardId"],
      getApp().globalData["shareCardId"] !== "" &&
        ["1011", "1047", "1048", "1049"].indexOf(String(scene)) >= 0,
    ]`);
    utils.logger([
      getApp().globalData["shareCardId"],
      getApp().globalData["shareCardId"] !== "" &&
        ["1011", "1047", "1048", "1049"].indexOf(String(scene)) >= 0,
    ]);
    if (
      getApp().globalData["shareCardId"] !== "" &&
      ["1011", "1047", "1048", "1049"].indexOf(String(scene)) >= 0
    ) {
      utils.logger(`扫描小程序码模式进入首页`);
    }

    if (
      (this.data.shareCardId !== "" &&
        ["1007", "1008"].indexOf(String(scene)) >= 0) ||
      (getApp().globalData["shareCardId"] !== "" &&
        ["1011", "1047", "1048", "1049"].indexOf(String(scene)) >= 0)
    ) {
      let shareCardId = !!this.data.shareCardId
        ? this.data.shareCardId
        : getApp().globalData["shareCardId"];
      this.setData({
        shareCardId,
      });
      utils.logger("将被识别的名片ID为:", shareCardId);
      utils.logger("getApp().globalData", getApp().globalData);
      this.getCardDetail(shareCardId);
      wx.showLoading({
        mask: true,
        title: "正在查询名片...",
      });
      getApp().globalData["scene"] = "1001";
    } else {
      this.getMyCards();
    }
  },
  ...utils.defaultShare,
  getCardDetail(cardId) {
    // 获取用户名片详情
    utils.logger("获取用户名片详情");
    utils
      .ajax("/v1/bcs/getBusinessCardWithHoldState.do ", {
        cardId: cardId,
      })
      .then(res => {
        if (res.code === "000000") {
          // 解析获取到的用户信息，跳转到详情页
          // 这里要检查是自己的名片还是别人的名片
          const myCards = getApp().globalData["myCards"];
          if (
            myCards.length == 0 ||
            myCards[0].cardId != res.data.cardInfo.cardId
          ) {
            // 是别人的名片，要判断名片持有状态
            utils.logger("是别人的名片，要判断名片持有状态");
            if (res.data.cardInfo.state == 0) {
              utils.logger(
                "既不在待接收列表，也不在已接收列表，需要预存到名片夹后再跳转",
              );
              this.preSave();
            } else {
              utils.logger("直接根据信息跳转");
              wx.hideLoading();
              this.setData({
                shareCardId: "",
              });
              wx.navigateTo({
                url:
                  "/pages/preview/preview?" +
                  utils.serializeUrl(res.data.cardInfo),
              });
            }
          } else {
            // 是自己的名片
            utils.logger("是自己的名片");
            wx.hideLoading();
            this.setData(
              {
                shareCardId: "",
              },
              () => {
                wx.navigateTo({
                  url:
                    "/pages/preview/preview?" +
                    utils.serializeUrl(res.data.cardInfo),
                });
              },
            );
          }
        } else {
          wx.hideLoading();
          utils.logger(res.message || "没有获取用户分享的名片信息");
        }
      })
      .catch(res => {
        wx.hideLoading();
      });
  },
  searchInputDoneEvent(event) {
    wx.navigateTo({
      url: "/pages/search/search?indexName=" + event.detail.search,
    });
  },
  preSave() {
    utils
      .ajax("/v1/bcs/preAddUserCardHolder.do", {
        cardId: this.data.shareCardId,
      })
      .then(res => {
        if (res.code === "000000") {
          wx.hideLoading();
          this.setData({
            shareCardId: "",
          });
          wx.navigateTo({
            url:
              "/pages/preview/preview?" +
              utils.serializeUrl(
                Object.assign({}, res.data.cardInfo, {
                  holderId: res.data.holderId,
                  state: res.data.state,
                }),
              ),
          });
        } else {
          utils.logger(res.message || "获取用户名片列表失败");
        }
      })
      .catch(res => {});
  },
  getMoreReciveList() {
    // 获取已接收名片
    utils
      .ajax("/v1/bcs/queryUserCardHolders.do", {
        pageNo: this.data.pageNo,
        pageSize: 10,
        orderType: this.data.orderType,
      })
      .then(res => {
        if (res.code === "000000") {
          const list = [...this.data.recivedCards, res.data.datas];
          this.setData({
            recivedCards: list,
            total: res.data.total,
          });
        } else {
          utils.logger(res.message || "获取已接收名片失败");
        }
      })
      .catch(res => {
        utils.message(res.message || "网络错误");
      });
  },
  showOrderControl() {
    this.setData({
      controlShow: true,
    });
  },
  hideOrderControl() {
    this.setData({
      controlShow: false,
    });
  },
  changOrder(event) {
    const key = event.currentTarget.dataset.key;
    this.setData(
      {
        controlShow: false,
        orderType: key,
      },
      () => {
        this.getReciveList();
      },
    );
  },
});
